﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

using Castle.Core.Logging;
using Castle.Core.Resource;

using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

namespace TVN.ShopMan.ApplicationInterface
{
    using TVN.Common.Interfaces;
    using TVN.ShopMan.Common;
    using TVN.ShopMan.ActiveModels;
    using TVN.ShopMan.ApplicationInterface.AppForms;

    static class Program
    {
        public static SessionInfo SessionData
        {
            get;
            set;
        }

        private static IWindsorContainer container = null;
        /// <summary>
        /// The container uses to resolve other services / components
        /// </summary>
        public static IWindsorContainer Container
        {
            get
            {
                return Program.container;
            }
        }

        private static ILogger logger = null;
        /// <summary>
        /// The root logger for application
        /// </summary>
        public static ILogger Logger
        {
            get
            {
                if (Program.logger == null)
                {
                    Program.logger = Program.container.Resolve<ILogger>();
                }
                return Program.logger;
            }
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // Initliaizes resources
            // From configuration file
            IResource resource = new AssemblyResource("assembly://AppConfig/Castle.config");
            Program.container = new WindsorContainer(new XmlInterpreter(resource));

            // From some assembly
            Program.container.Register(
                AllTypes.FromAssemblyNamed("TVN.ShopMan.ActiveImpl.Repositories")
                        .Pick()
                        .WithService.FirstInterface()
                );

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

            AuthForm authForm = new AuthForm();
            DialogResult authResult = authForm.ShowDialog();
            if (authResult == DialogResult.OK)
            {
                Application.Run(new MainForm());
                Program.container.Dispose();
            }
            else
            {
                Program.container.Dispose();
                Application.Exit();
            }
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Program.logger.Fatal("ThreadException", e.Exception);
        }
    }
}
